import { useCallback, useRef } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { fabric } from 'fabric';
import { RootState } from '../store';
import {
  setCurrentImage,
  setProcessing,
  updateFilters,
  addToHistory,
  undo,
  redo,
} from '../store/slices/imageSlice';
import { ImageService } from '../services/imageService';
import { ProcessingOptions } from '../types';

export const useImageProcess = () => {
  const dispatch = useDispatch();
  const { currentImage, isProcessing, filters, fabricCanvas } = useSelector(
    (state: RootState) => state.image
  );
  const canvasRef = useRef<HTMLCanvasElement>(null);

  const processImage = useCallback(
    async (options: ProcessingOptions) => {
      if (!currentImage) return;

      dispatch(setProcessing(true));
      try {
        const result = await ImageService.processImage(currentImage, options);
        if (result.success && result.data) {
          dispatch(addToHistory(currentImage));
          dispatch(setCurrentImage(result.data));
        } else {
          console.error('图像处理失败:', result.error);
        }
      } catch (error) {
        console.error('图像处理错误:', error);
      } finally {
        dispatch(setProcessing(false));
      }
    },
    [currentImage, dispatch]
  );

  const applyFilters = useCallback(
    (newFilters: Partial<typeof filters>) => {
      dispatch(updateFilters(newFilters));
      
      if (canvasRef.current && fabricCanvas) {
        const canvas = canvasRef.current;
        ImageService.applyFilters(canvas, { ...filters, ...newFilters });
        
        // 更新Fabric.js画布
        fabricCanvas.renderAll();
      }
    },
    [filters, fabricCanvas, dispatch]
  );

  const enhanceImage = useCallback(() => {
    return processImage({ type: 'enhance' });
  }, [processImage]);

  const removeBackground = useCallback(() => {
    return processImage({ type: 'background-remove' });
  }, [processImage]);

  const upscaleImage = useCallback((scale: number = 2) => {
    return processImage({ type: 'upscale', parameters: { scale } });
  }, [processImage]);

  const denoiseImage = useCallback(() => {
    return processImage({ type: 'denoise' });
  }, [processImage]);

  const undoAction = useCallback(() => {
    dispatch(undo());
  }, [dispatch]);

  const redoAction = useCallback(() => {
    dispatch(redo());
  }, [dispatch]);

  const exportImage = useCallback(
    async (format: 'png' | 'jpg' | 'webp' = 'png') => {
      if (!fabricCanvas) return null;

      const dataURL = fabricCanvas.toDataURL({
        format: format === 'jpg' ? 'jpeg' : format,
        quality: 0.9,
      });

      return dataURL;
    },
    [fabricCanvas]
  );

  const downloadImage = useCallback(
    async (filename: string = 'processed-image', format: 'png' | 'jpg' | 'webp' = 'png') => {
      const dataURL = await exportImage(format);
      if (!dataURL) return;

      const link = document.createElement('a');
      link.download = `${filename}.${format}`;
      link.href = dataURL;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },
    [exportImage]
  );

  return {
    currentImage,
    isProcessing,
    filters,
    canvasRef,
    processImage,
    applyFilters,
    enhanceImage,
    removeBackground,
    upscaleImage,
    denoiseImage,
    undoAction,
    redoAction,
    exportImage,
    downloadImage,
  };
};